<script lang="jsx">
/**
 * @author lilinjie
 * @Description:
 */

import { defineComponent, onMounted, ref } from 'vue'
import { useList } from '@/hooks/common/useList'
import { useCuModal } from '@/hooks/common/useCuModal'
import {
  columns,
  productAuditStatusMap,
  productAuditStatusOptions,
  productSKU,
  productStatusMap,
  productStatusOptions
} from '@/config/product'
import { useProvideData } from '@/context/product/product'
import CategoryModal from './modal.vue'
import ProductSkuModal from './sku-modal.vue'
import {
  deleteProduct,
  getAllProducts,
  getProductByCondition, insertProduct,
  updateProduct,
  updateProductOnSaleStatus
} from '@/api/product'
import { message } from 'ant-design-vue'
import { formatTime } from '@/utils/time'
import { useProductSkuTable } from '@/hooks/product/sku'
import { useProvideSkuData } from '@/context/product/sku'

export default defineComponent({
  name: 'Category',
  setup() {
    // 表单部分
    const {
      filterForm,
      clearForm,
      handleSearch,
      tableData,
      pagination,
      handleCurrentChange,
      handleSizeChange
    } = useList({
      defaultFilterForm: {
        status: undefined,
        auditStatus: undefined,
        name: undefined,
        category1Id: undefined,
        brandId: undefined
      },
      getList: ({ onSuccess }) => {
        getProductByCondition({ ...filterForm, ...pagination }).then(res => {
          onSuccess({
            list: res.data.list?.map((item, index) => {
              return { ...item.product, key: index, productSkuList: item?.productSkuList, index: index + 1 }
            }).flat(),
            total: res.data.total
          })
        })
      }
    })

    // 弹窗部分
    const {
      cuFilterForm,
      modelData,
      isEdit,
      onClickClose,
      onClickConfirm,
      onClickCreate,
      onClickEdit,
      onClickView
    } = useCuModal({
      defaultCuFilterForm: {
        id: undefined,
        name: undefined,
        brandId: undefined,
        category1Id: undefined,
        imgUrl: undefined,
        description: undefined,
        itemNum: undefined,
        status: undefined,
        auditStatus: undefined
      },
      create({ cuFilterForm, onSuccess }) {
        console.log('create', cuFilterForm)
        insertProduct({ product: cuFilterForm, productSkuList: null }).then(res => {
          console.log(res)
          onSuccess()
          handleSearch()
        })
      },
      update({ cuFilterForm, currentId, onSuccess }) {
        updateProduct({ product: cuFilterForm, productSkuList: null }).then(res => {
          console.log(res)
          onSuccess()
          handleSearch()
        }).catch(err => {
          console.log(err)
          message.error('修改失败')
        })
        console.log('update', cuFilterForm)
      }
    })

    // 提供上下文
    useProvideData({
      cuFilterForm,
      modelData,
      isEdit,
      onClickClose,
      onClickConfirm,
      onClickCreate,
      onClickEdit,
      onClickView
    })

    onMounted(() => {
      handleSearch()
    })

    const onClickDelete = (id) => {
      console.log(id)
      deleteProduct(id).then(res => {
        handleSearch()
        console.log(res)
      })
    }

    const {
      skuFilterForm,
      skuModelData,
      skuOnEdit,
      skuOnClickClose,
      skuOnClickConfirm,
      skuOnClickCreate,
      skuOnClickEdit,
      skuOnClickView
    } = useProductSkuTable({ handleSearch })

    // 提供sku上下文
    useProvideSkuData({
      skuFilterForm,
      skuModelData,
      skuOnEdit,
      skuOnClickClose,
      skuOnClickConfirm,
      skuOnClickCreate,
      skuOnClickEdit,
      skuOnClickView
    })

    return () => {
      const tableSlot = {
        bodyCell: ({ text, record, index, column }) => {
          if (column.dataIndex === 'action') {
            return <a-space>
              <a-button type="link" size="small" onClick={() => onClickView(record)}>查看</a-button>
              <a-button type="link" size="small">
                <a-popconfirm title="是否上架该商品吗？" ok-text="确认" cancel-text="取消"
                              onConfirm={() => updateProductOnSaleStatus({ id: record.id, status: 1 }).then(res => {
                                console.log(res)
                                message.success('上架成功')
                              })}
                >
                  上架
                </a-popconfirm>
              </a-button>
              <a-button type="primary" size="small" onClick={() => {
                skuFilterForm.productId = record.id
                skuOnClickCreate()
              }}
              >添加sku
              </a-button>
              <a-button type="primary" size="small" onClick={() => onClickEdit(record)}>编辑</a-button>
              <a-button danger size="small">
                <a-popconfirm title="你确认删除该商品吗？" ok-text="确认" cancel-text="取消"
                              onConfirm={() => onClickDelete(record.id)}
                >
                  删除
                </a-popconfirm>
              </a-button>
            </a-space>
          }

          if (column.dataIndex === 'imgUrl') {
            return <a href={text} target="_blank" class="img-box">
              <img src={text} class="img" />
              <span class="img-text">{text}</span>
            </a>
          }

          if (column.dataIndex === 'createTime') {
            return <span>{text?.split('T')[0] + ' ' + text?.split('T')[1].split('.')[0]}</span>
          }

          if (column.dataIndex === 'status') {
            return <span class={`status status-${text}`}>{productStatusMap[text]}</span>
          }

          if (column.dataIndex === 'auditStatus') {
            return <span class={`status audit-status-${text}`}>{productAuditStatusMap[text]}</span>
          }
        },

        expandedRowRender: ({ record, index }) => {
          console.log(tableData?.data.list?.skuList, tableData?.data.list?.indexList, index)
          return <a-table className="table"
                          columns={productSKU}
                          dataSource={record?.productSkuList}
                          v-slots={innerTableSlot}

          />
        }
      }

      const innerTableSlot = {
        bodyCell: ({ text, record, index, column }) => {
          if (column.dataIndex === 'createTime') {
            return <span>{formatTime(text)}</span>
          }

          if (column.dataIndex === 'action') {
            return <a-space>
              <a-button type="link" size="small" onClick={() => {
                skuOnClickView(record)
                console.log(skuModelData)
              }}
              >查看
              </a-button>
              <a-button type="primary" size="small" onClick={() => skuOnClickEdit(record)}>编辑</a-button>
            </a-space>
          }

          if (column.dataIndex === 'imgUrl') {
            return <a href={text} target="_blank" class="img-box">
              <img src={text} class="img" />
              <span class="img-text">{text}</span>
            </a>
          }

          if (column.dataIndex === 'createTime') {
            return <span>{text?.split('T')[0] + ' ' + text?.split('T')[1].split('.')[0]}</span>
          }
        }
      }

      return (
          <div class="product">
            <div class="header">
              <a-form class="form" layout="inline">
                <a-form-item label="商品名称">
                  <a-input placeholder="请输入ID" onChange={handleSearch} vModel:value={filterForm.name} />
                </a-form-item>
                <a-form-item label="状态">
                  <a-select placeholder="请选择状态" options={productStatusOptions} style={{ width: '150px' }} onChange={handleSearch} vModel:value={filterForm.status} />
                </a-form-item>
                <a-form-item label="审核状态">
                  <a-select placeholder="状态" options={productAuditStatusOptions} style={{ width: '150px' }} onChange={handleSearch} vModel:value={filterForm.auditStatus} />
                </a-form-item>
                <a-form-item label="分类id">
                  <a-input placeholder="请输入ID" onChange={handleSearch} vModel:value={filterForm.category1Id} />
                </a-form-item>
                <a-form-item label="商品id">
                  <a-input placeholder="请输入ID" onChange={handleSearch} vModel:value={filterForm.brandId} />
                </a-form-item>
                <a-space>
                  <a-button onClick={() => {
                    clearForm()
                    handleSearch()
                  }}
                  >重置
                  </a-button>
                  <a-button onClick={handleSearch}>查询</a-button>
                </a-space>
              </a-form>
              <a-button type="primary" onClick={onClickCreate}>添加商品</a-button>
            </div>
            <a-table class="table"
                     columns={columns}
                     dataSource={tableData?.data.list}
                     v-slots={tableSlot}
            />
            <CategoryModal />
            <ProductSkuModal />
          </div>
      )
    }
  }
})
</script>

<style lang="less">
@import '@/assets/less/common-style.less';

.product {
  .header {
    .flex(space-between);

    .ant-btn-primary {
      margin-right: 50px;
    }
  }

  .table {
    padding: 0 24px;
    height: calc(100vh - @nav-bar-height - 60px);
    overflow: auto;
  }

  .form {
    margin: 20px 50px;
  }
}

.img-box {
  .common-img-box();
}

.status {
  display: inline-block;
  //width: 100px;
  //height: 20px;
  line-height: 20px;
  padding: 2px 10px;
  text-align: center;
  border-radius: 8px;
  //background-color: #4caf50;
  color: #fff;
  font-size: 12px;
  white-space: nowrap;
}
.status-1 {
  background-color: #4caf50;
}
.status-3 {
  background-color: #ff9800;
}
.status-2 {
  background-color: #2196f3;
}
.status-0 {
  background-color: gray;
}

.audit-status-1 {
  background-color: #5a7c5a;
}
.audit-status-0 {
  background-color: #ff9800;
}
.audit-status-2 {
  background-color: #2196f3;
}
</style>
